import * as common from '../common/index.js';
export function call() {
  console.log('copy-left !!!');
}
/**
 * 判断元素全部出现在可视区域
 * @param  el- dom节点
 */
export const isInView = (el) => {
  var rect = el.getBoundingClientRect();

  var elemTop = rect.top;

  var elemBottom = rect.bottom;

  // 元素全部出现在视窗
  var isVisible = elemTop >= 0 && elemBottom <= window.innerHeight;

  return isVisible;
};
/**
 * 判断元素出现在可视区域
 * @param el- dom节点
 */
export const isInViewShow = (el) => {
  var rect = el.getBoundingClientRect();

  var elemTop = rect.top;

  var elemBottom = rect.bottom;

  // 元素出现在可视区域
  var isVisible = elemTop >= 0 && elemBottom - rect.height <= window.innerHeight;

  return isVisible;
};
export const pro = new Promise((resolve, reject) => {
  resolve(1);
  reject(2);
});
export const sym = Symbol();
/**
 * 实现数字滚动的效果的类
 */
export class DigitScroll {
  constructor(options) {
    //获取容器的DOM，没有则抛出错误
    this.container = document.querySelector(options.container);
    if (!this.container) {
      throw Error('no container');
    }
    this.container.style.overflow = 'hidden';
    this.container.style.display = 'flex';
    //可视容器高度 也是滚动间隔距离,容器要设置高度，否则默认30px
    this.rollHeight = parseInt(getComputedStyle(this.container).height) || 30;
    this.container.style.height = this.rollHeight + 'px';
  }
  roll(num) {
    // 将传入的要滚动的数字拆分后初始化每一位数字的容器
    this.initDigitEle(num);
    const numEles = this.container.querySelectorAll('.single-num');
    // 遍历生成每一位数字的滚动队列，如滚动到7，则生成内容为0，1，2，3，4，5，6，7的7个div，用于滚动动画
    [...numEles].forEach((numEle, index) => {
      const curNum = 0;
      let targetNum = Number(this.numberArr[index]);
      if (curNum >= targetNum) {
        targetNum = targetNum + 10;
      }
      let cirNum = curNum;
      // 文档碎片，拼凑好后一次性插入节点中
      const fragment = document.createDocumentFragment();
      // 生成从0到目标数字对应的div
      while (targetNum >= cirNum) {
        const ele = document.createElement('div');
        ele.innerHTML = cirNum % 10;
        cirNum++;
        fragment.appendChild(ele);
      }
      numEle.innerHTML = '';
      numEle.appendChild(fragment);
      //重置位置
      numEle.style.cssText += '-webkit-transition-duration:0s;-webkit-transform:translateY(0)';
      setTimeout(() => {
        numEle.style.cssText += `-webkit-transition-duration:1s;-webkit-transform:translateY(${-(targetNum - curNum) * this.rollHeight}px);`;
      }, 50);
    });
  }
  // 初始化容器
  initDigitEle(num) {
    // 数字拆分位数
    const numArr = num.toString().split('');
    // 文档碎片，拼凑好后一次性插入节点中
    const fragment = document.createDocumentFragment();
    numArr.forEach((item) => {
      const el = document.createElement('div');
      // 数字是要滚动的，非数字如.是不滚动的
      if (/[0-9]/.test(item)) {
        el.className = 'single-num';
        el.style.height = this.rollHeight + 'px';
        el.style.lineHeight = this.rollHeight + 'px';
      } else {
        el.innerHTML = item;
        el.className = 'no-move';
        el.style.verticalAlign = 'bottom';
      }
      // el.style.float='left';
      fragment.appendChild(el);
    }, []);
    this.container.innerHTML = '';
    this.container.appendChild(fragment);
    // 存储滚动的数字
    this.numberArr = numArr.filter((item) => /[0-9]/.test(item));
  }
}
/**
 * 实现防抖函数
 */
export function debounce(fn, delay = 500) {
  let timer;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    const args = arguments;
    timer = setTimeout(() => {
      fn.apply(this, args); // 改变this指向为调用debounce所指的对象
    }, delay);
  };
}

/**
 * 实现节流函数
 */
export function throttle(fn, delay = 200) {
  let flag = true;
  return function () {
    if (!flag) return;
    flag = false;
    const args = arguments;
    setTimeout(() => {
      fn.apply(this, args);
      flag = true;
    }, delay);
  };
}

/**
 * 将DOM转化成树结构对象
 */
export function dom2tree(dom) {
  const obj = {};
  obj.tag = dom.tagName;
  obj.children = [];
  dom.childNodes.forEach((child) => obj.children.push(dom2tree(child)));
  return obj;
}

/**
 * 将树结构转换为DOM
 */
export function _render(vnode) {
  // 如果是数字类型转化为字符串
  if (typeof vnode === 'number') {
    vnode = String(vnode);
  }
  // 字符串类型直接就是文本节点
  if (typeof vnode === 'string') {
    return document.createTextNode(vnode);
  }
  // 普通DOM
  const dom = document.createElement(vnode.tag);
  if (vnode.attrs) {
    // 遍历属性
    Object.keys(vnode.attrs).forEach((key) => {
      const value = vnode.attrs[key];
      dom.setAttribute(key, value);
    });
  }
  // 子数组进行递归操作
  vnode.children.forEach((child) => dom.appendChild(_render(child)));
  return dom;
}

export function trans_base64(url, fn) {
  const img = url; //imgurl 就是你的图片路径

  function getBase64Image(img) {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);
    const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
    const dataURL = canvas.toDataURL('image/' + ext);
    return dataURL;
  }

  const image = new Image();
  image.src = img;
  image.onload = function () {
    var base64 = getBase64Image(image);
    console.log(base64);
    fn(base64);
  };
}
/**
 * Because it's so fucking difficult to detect the scrolling element, just move them all
 * @param {number} amount
 */
function move(amount) {
  document.documentElement.scrollTop = amount;
  document.body.parentNode.scrollTop = amount;
  document.body.scrollTop = amount;
}
function position() {
  return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop;
}
var requestAnimFrame = (function () {
  return (
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function (callback) {
      window.setTimeout(callback, 1000 / 60);
    }
  );
})();
/**
 * @param {number} to
 * @param {number} duration
 * @param {Function} callback
 */
export function scrollTo(to, duration, callback) {
  const start = position();
  const change = to - start;
  const increment = 20;
  let currentTime = 0;
  duration = typeof duration === 'undefined' ? 500 : duration;
  var animateScroll = function () {
    // increment the time
    currentTime += increment;
    // find the value with the quadratic in-out easing function
    var val = Math.easeInOutQuad(currentTime, start, change, duration);
    // move the document.body
    move(val);
    // do the animation unless its over
    if (currentTime < duration) {
      requestAnimFrame(animateScroll);
    } else {
      if (callback && typeof callback === 'function') {
        // the animation is done so lets callback
        callback();
      }
    }
  };
  animateScroll();
}

export function file_upload(files) {
  let form = new FormData();
  for (const item of files) {
    form.append('file', item);
  }
  return form;
}
// 除图片外的通用下载
// window.location.href = 'http://localhost:4000/public/1618880090660community.xlsx'
export function file_down(blob, name) {
  let url = URL.createObjectURL(blob);
  let body = document.body;
  let a = document.createElement('a');
  body.appendChild(a);
  a.setAttribute('href', url);
  a.setAttribute('download', name);
  a.click();
}
export function file_down1(blob) {
  let url = URL.createObjectURL(blob);
  window.location.href = url;
}

export function judeg_sf(val) {
  let reg = /^(SF[0-9]+):[0-9]{4}/g;
  return reg.test(val);
}

export function judeg_fc(val) {
  let reg = /^([a-zA-Z]{2}202)\d+/;
  return reg.test(val);
}

export const scrollToBottom = {
  getScrollTop: function () {
    var scrollTop = 0,
      bodyScrollTop = 0,
      documentScrollTop = 0;
    if (document.body) {
      bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
      documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = bodyScrollTop - documentScrollTop > 0 ? bodyScrollTop : documentScrollTop;
    return scrollTop;
  },
  getScrollHeight: function () {
    var scrollHeight = 0,
      bodyScrollHeight = 0,
      documentScrollHeight = 0;
    if (document.body) {
      bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
      documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = bodyScrollHeight - documentScrollHeight > 0 ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
  },
  getClientHeight: function () {
    var windowHeight = 0;
    if (document.compatMode == 'CSS1Compat') {
      windowHeight = document.documentElement.clientHeight;
    } else {
      windowHeight = document.body.clientHeight;
    }
    return windowHeight;
  },
  onScrollEvent: function (callback) {
    var This = this;
    window.onscroll = function () {
      if (This.getScrollTop() + This.getClientHeight() >= This.getScrollHeight() - 10) {
        callback();
      }
    };
  }
};

export const fn_common = common;
